from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.db import transaction

from artmarket.models import Order
from artmarket.permissions.purchase_permission import IsBuyer
from artmarket.serializers import OrderSerializer
from users.models import CustomUser


class PurchaseArtworkView(APIView):
    permission_classes = [IsBuyer]
    """
    购买艺术品, 将购物车艺术品的artist字段设置为当前购买的买家
    """

    def get(self, request):
        """
        获取当前用户的购物车（待支付的订单列表）
        """
        user_id = request.user.id
        orders = Order.objects.filter(buyer_id=user_id, status=Order.ORDER_PENDING)
        serializer = OrderSerializer(instance=orders, many=True)
        return Response(data={
            'results': serializer.data
        }, status=status.HTTP_200_OK)

    @transaction.atomic
    def post(self, request):
        """
        结算购物车
        """
        user = request.user
        buyer_id = user.id

        # 获取选中的订单ID列表
        selected_order_ids = request.data.get('selected_order_ids', [])

        if not selected_order_ids:
            return Response({'message': '未选择订单'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            with transaction.atomic():
                # 获取选中的订单
                selected_orders = Order.objects.filter(id__in=selected_order_ids, buyer_id=buyer_id,
                                                       status=Order.ORDER_PENDING)
                if not selected_orders:
                    return Response({'message': '选中的订单不存在'}, status=status.HTTP_400_BAD_REQUEST)

                # 遍历选中的订单
                for order in selected_orders:
                    artwork = order.artwork

                    # 更改订单状态为已完成
                    order.status = Order.ORDER_COMPLETED
                    order.save()

                    # 更新艺术品的 artist 为买家的 ID
                    artwork.artist_id = buyer_id
                    artwork.save()

                return Response({"message": "结算成功"}, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({"message": str(e)}, status=status.HTTP_400_BAD_REQUEST)
